<template>
  <div style="width: 100%; height: 100%" v-loading="props.loading">
    <el-auto-resizer>
      <template #default="{ height, width }">
        <ElTableV2
          v-bind="{ ...props.config }"
          @scroll="props.onScroll"
          :width="props.autoSize ? width : props.width"
          :height="props.autoSize ? height : props.height"
          :columns="props.columns"
          :data="props.data"
          :fixed-data="props.fixedData || []"
          ref="tableRef"
          @end-reached="handelFinishRender"
        >
          <template #row="props">
            <Row v-bind="props" />
          </template>
        </ElTableV2>
      </template>
    </el-auto-resizer>
  </div>
</template>

<script lang="ts" setup>
import { ElTableV2, TableV2Instance, TableV2Props } from 'element-plus';
import { cloneVNode, ref } from 'vue';

export type IRowsRenderedParams = {
  rowCacheStart: number;
  rowCacheEnd: number;
  rowVisibleStart: number;
  rowVisibleEnd: number;
};
const tableRef = ref<TableV2Instance | null>(null);
export type MVirtualizedTableProps = Partial<Omit<TableV2Props, 'width' | 'height' | 'columns' | 'data'>>;
const props = withDefaults(
  defineProps<{
    width: number;
    height: number;
    data: TableV2Props['data'];
    columns: TableV2Props['columns'];
    onScroll?: (e: any) => void;
    fixedData?: TableV2Props['fixedData'];
    config: MVirtualizedTableProps;
    autoSize?: boolean;
    loading?: boolean;
  }>(),
  {
    onScroll: () => {},
    autoSize: false,
    loading: false,
  },
);
const handelFinishRender = () => {
  emit('renderFinish');
};
const emit = defineEmits<{
  (e: 'renderFinish'): void;
}>();
// const handelRowRender = (e: IRowsRenderedParams) => {
//   if (e.rowVisibleEnd >= props.data.length - 1) {
//   emit('renderFinish', e);
//   }
// };
const getTableInstance = () => {
  return tableRef.value;
};
const Row = ({ rowData, rowIndex, cells, columns }: { rowData: any; rowIndex: number; cells: any; columns: any }) => {
  // 遍历所有列，检查是否有 rowSpan 方法
  columns.forEach((column: any, columnIndex: number) => {
    if (column.rowSpan && typeof column.rowSpan === 'function') {
      try {
        const rowSpan = column.rowSpan({ rowData, rowIndex });

        if (rowSpan > 1) {
          const cell = cells[columnIndex];
          if (cell) {
            const style = {
              ...cell.props.style,
              backgroundColor: '#fff', // 不加这个会有bug 很奇怪
              height: `${rowSpan * 50 - 1}px`,
              alignSelf: 'flex-start',
              zIndex: 1,
            };
            cells[columnIndex] = cloneVNode(cell, { style });
          }
        }
      } catch (error) {
        console.warn('Row span error:', error);
      }
    }
  });
  return cells;
};

defineExpose({ getTableInstance });
</script>
<style></style>
